package com.example.study.commen.websocket;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.study.commen.websocket.bean.WebSocketVO;
import com.example.study.controller.RabbitmqController;
import com.example.study.plus.mybatis_plus.entity.ChatMessages;
import com.example.study.plus.mybatis_plus.service.ChatMessagesService;
import com.example.study.rabbitmq.config.RabbitmqInfo;
import com.github.linyuzai.connection.loadbalance.websocket.concept.WebSocketLoadBalanceConcept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author： xxt
 * @date： 2022/5/23 16:27
 * @Description： WebSocket操作类
 */
@ServerEndpoint(value = "/websocket/{userId}",encoders = {HashMapEncoder.class, BaseModelEncoder.class})
@Component
@Slf4j
public class WebSocketSever {

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // session集合,存放对应的session
    private static ConcurrentHashMap<Integer, Session> sessionPool = new ConcurrentHashMap<>();

    // concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
    private static CopyOnWriteArraySet<WebSocketSever> webSocketSet = new CopyOnWriteArraySet<>();


    /**
     * 建立WebSocket连接
     *
     * @param session
     * @param userId  用户ID
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Integer userId) {
        log.info("WebSocket建立连接中,连接用户ID：{}", userId);
        try {
            Session historySession = sessionPool.get(userId);

            // historySession不为空,说明已经有人登陆账号,应该删除登陆的WebSocket对象
            if (historySession != null) {
                webSocketSet.remove(historySession);
                historySession.close();
            }
        } catch (IOException e) {
            log.error("重复登录异常,错误信息：" + e.getMessage(), e);
        }
        // 建立连接
        this.session = session;
        webSocketSet.add(this);
        sessionPool.put(userId, session);
        log.info("建立连接完成,当前在线人数为：{}", webSocketSet.size());
    }

    /**
     * 发生错误
     *
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("连接断开,当前在线人数为：{}", webSocketSet.size());
    }

    /**
     * 接收客户端消息
     *
     * @param message 接收的消息
     */
    @OnMessage(maxMessageSize = 1024)
    public void onMessage(String message) {

        try {
            log.info("收到客户端发来的消息：{}", message);
//            WebSocketVO vo = JSONObject.parseObject(message, WebSocketVO.class);
//            if (null != vo.getMessage()) {
//                sendMessageByUser(vo.getTargetId(), vo);
//            } else {
//                log.info("客户端心跳或者连接信息" + message);
//            }

        } catch (JSONException e) {
            log.info("客户端心跳或者连接信息" + message);
        }

    }


    /**
     * 推送消息到指定用户
     *
     * @param message 发送的消息
     */
    public String sendMessageByUser(WebSocketVO message) {

        log.info("用户ID：" + message.getFromId() + ",推送内容：" + JSONObject.toJSONString(message));

        Session session = sessionPool.get(message.getTargetId());
        String result = "";

        if (null == session) {
            log.error("指定id" + message.getTargetId() + "不在线");
            return "offline";
        }
        try {

            session.getBasicRemote().sendText(JSONObject.toJSONString(message));
            result = "success";

        }catch (java.lang.IllegalStateException e) {
            result = "offline";
        } catch (Exception e) {
            log.error("推送消息到指定用户发生错误：" + e.getMessage(), e);
            result = e.getMessage();
        }
        return result;
    }

    /**
     * 群发消息
     *
     * @param message 发送的消息
     * @return 0成功，1有失败
     */
    public static Integer sendAllMessage(String message) {
        log.info("发送消息：{}", message);
        int status = 0;
        for (WebSocketSever webSocket : webSocketSet) {
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("群发消息发生错误：" + e.getMessage(), e);
                status = 1;
            }
        }
        return status;
    }

}

